#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<pthread.h>
#include<functional>
#include"ThreadPool.hpp"

#include "InetAddr.hpp"
#include "nocopy.hpp"
#include "Log.hpp"
#include "comm.hpp"

//设置一个聊天室，如果不在列表，就添加

//const std::string default_ip = "0.0.0.0";
const uint16_t default_port = 8888;
const int default_sockfd = -1;
const int default_bufferSize = 1024;

//定义函数类型
//using task_t =std::function<void(int socket,const std::string& message )>;
using task_t =std::function<void()>;

class UdpServer : public nocopy
{
public:
    // UdpServer(const std::string &ip = default_ip, uint16_t port = default_port)
    //     : _ip(default_ip), _port(default_port), _sockfd(default_sockfd)
    // {
    // }

    // UdpServer(cb_t onMessage ,uint16_t port = default_port)
    //     : On_Message(onMessage) ,_port(default_port), _sockfd(default_sockfd)
    // {
    // }

    UdpServer(uint16_t port = default_port)
        : _port(default_port), _sockfd(default_sockfd)
    {
        pthread_mutex_init(&user_lock,nullptr);
    }
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.LogMessage(Fatal, "socket error,%d : %s\n", errno, strerror(errno));
            exit(Socket_error);
        }
        lg.LogMessage(Info, "socket is created ,socketfd %d\n", _sockfd);

        // 创建网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        //服务器ip由系统绑定
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr =INADDR_ANY;

        // 绑定到网络
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "socoket bind error,%d : %s\n", errno, strerror(errno));
            exit(Bind_error);
        }

        ThreadPool<task_t>::Getinstance()->Start();
        lg.LogMessage(Info, "tack running...\n");
    }

    void Start()
    {
        char buffer[default_bufferSize];
        // 启动了就不会停下
        while (true)
        {
            // 获取对方的信息
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 默认为字符串
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                // // 转发功能
                // InerAddr addr(peer);
                // buffer[default_bufferSize] = 0;
                // std::string response=On_Message(buffer);
                // //std::cout <<"[" <<addr.PrintDebug()<<"]"<< buffer << std::endl;
                
                //sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
                //添加在线用户
                InerAddr addr(peer);
                AddOnlineUser(addr);
                buffer[n] = 0;
                std::string message="[";
                message+=addr.IP().c_str();
                message+=":";
                message+=std::to_string(addr.Port());
                message+="]";
                message+=buffer;
                
                task_t task = std::bind(&UdpServer::Route, this, _sockfd, message);
                ThreadPool<task_t>::Getinstance()->Push(task);
            }
        }
    }
    void AddOnlineUser(InerAddr &addr)
    {
        LockGuard lockguard(&user_lock);
        for( auto &us : online_user)
        {
            //存在就不添加
            if(addr.operator=(us))
                return ;
        }
        online_user.push_back(addr);
        lg.LogMessage(Debug, "%s:%d is add to onlineuser list...\n", addr.IP().c_str(), addr.Port());
    }

    //服务器将消息转发
    void Route(int socket,std::string& message)
    {
        //加锁保护
        LockGuard lockguard(&user_lock);
        for(auto &us:online_user)
        {
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&us.GetAddr(), sizeof(us.GetAddr()));
            lg.LogMessage(Debug,"server send message to %s:%d ,message:%s\n",us.IP().c_str(),us.Port(),message.c_str());
        }
    }

    ~UdpServer()
    {
        pthread_mutex_destroy(&user_lock);
    }

private:
    //std::string _ip;
    uint16_t _port;
    int _sockfd;

    std::vector<InerAddr> online_user;
    pthread_mutex_t user_lock;


    //cb_t On_Message;//回调
};
